package com.cwj.config.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
////                    .antMatchers(HttpMethod.GET,"/employee/**").hasRole("USER")//基于角色授权
//                .antMatchers(HttpMethod.GET,"/user/**").hasRole("USER")//基于权限授权
//                .antMatchers(HttpMethod.POST,"/admin/**").hasRole("ADMIN")
//                .anyRequest().authenticated()
//                .and().httpBasic()
//                .and().csrf().disable();
        http.authorizeRequests()
                .antMatchers("/api/guest").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic()
                .and().addFilter(new JwtAuthenticateFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().csrf().disable();
    }
    @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user").password(encoder().encode("123456")).roles("USER").build());
        manager.createUser(User.withUsername("admin").password(encoder().encode("123456")).roles("ADMIN").build());
        return manager;
    }

    @Bean
    public static PasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
}
